<template>
	<section v-loading="listLoading">
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.content" clearable placeholder="名称"></el-input>
				</el-form-item>
				<el-form-item class="fr">
				    <el-button type="primary" size="medium" plain @click="handleAdd">新增</el-button>
			   </el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="users" stripe highlight-current-row border @selection-change="selsChange" style="width: 100%;">
            <el-table-column prop="indexId" label="ID" min-width="40" align="center">
			</el-table-column>
			<el-table-column prop="indexName" label="名称" min-width="60" align="center">
			</el-table-column>
			<el-table-column prop="indexDescription" label="描述" min-width="60" align="center">
			</el-table-column>
			<el-table-column prop="sort" label="排序" min-width="60" align="center">
			</el-table-column>
			<el-table-column label="视频" width="80" align="center">
		        <template slot-scope="scope">
	                <el-button size="small" @click="handlePlay(scope.row)" v-if="scope.row.indexImgUrl" type="text">查看视频</el-button>
	                <span v-else>暂无视频</span>
	            </template>
		    </el-table-column>
			<!--<el-table-column prop="indexImgUrl" label="图片" align="center" min-width="100">
				<template slot-scope="scope">
                    <el-popover placement="top-start" title="" trigger="click">
                        <img :src="scope.row.indexImgUrl" alt="" style="width: 500px">
                        <img slot="reference" :src="scope.row.indexImgUrl" style="width: 50px;height: 50px;border-radius: 5px;object-fit: cover;">
                    </el-popover>
                </template>
            </el-table-column>-->
			<!--<el-table-column prop="sort" label="排序" min-width="60" align="center">
			</el-table-column>-->
			<el-table-column label="操作" min-width="100" align="center">
				<template slot-scope="scope">
					<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="mini" plain @click="handleDel(scope.row.indexId)">删除</el-button>
					<el-button size="mini" type="success" plain @click="indexChild(scope.$index, scope.row, 'indexChild')">二级</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<!--<el-button size="small" type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>-->
			<el-pagination layout="prev, pager, next, jumper" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>
		<!--新增界面-->
		<el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false" width="500px">
			<el-form :model="addForm" label-width="80px" ref="addForm">
				<el-form-item label="名称" prop="indexName"  :rules="[{ required: true, message: '请填写名称', trigger: 'blur' }]">
                    <el-input v-model="addForm.indexName" />
                </el-form-item>
                <el-form-item label="描述" prop="indexDescription" :rules="[{ required: true, message: '请填写描述', trigger: 'blur' }]">
                    <el-input v-model="addForm.indexDescription"/>
                </el-form-item>
                <el-form-item label="排序" prop="sort" :rules="[{ required: true, message: '请填写排序', trigger: 'blur' }]">
                    <el-input v-model="addForm.sort"/>
                </el-form-item>
				<!--<el-form-item label="图片:" prop="indexImgUrl" :rules="[{ required: true, message: '请上传图片', trigger: 'blur' }]">
					<el-upload class="avatar-uploader photo" list-type="picture-card" :http-request="(res)=>{return Upload1(res, 'indexImgUrl')}" :multiple="false" :show-file-list="false" action="" :before-upload="beforeAvatarUpload" accept="image/jpeg,image/png">
						<img v-if="addForm.indexImgUrl" :src="addForm.indexImgUrl" class="avatar" width="145" height="145">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>-->
				<el-form-item label="视频">
					<div v-if="addForm.videoUrl" class="uploadVideo">
						<video :src="addForm.indexImgUrl" :poster="addForm.vodPhoto" controls style="width: 360px;height: 180px;"></video>
						<img class="uploadImgItemDel" @click="handleDelUrl(0)" src="http://blyw.oss-cn-hangzhou.aliyuncs.com/webStorage/web_1619754060794173.png"/>
					</div>
					<el-upload v-if="!addForm.indexImgUrl" action :http-request="Upload" :on-preview="handlePreview" :before-remove="beforeRemove" :on-remove="handleRemove" :on-success="handleSuccess" :on-exceed="handleExceed" drag :limit="limit" :file-list="fileList" >
				        <i class="el-icon-upload" ></i>
				        <div class="el-upload__text">
					                       将视频拖到此处，或
					        <em>点击上传</em>
				        </div>
			            <div slot="tip" class="el-upload__tip">上传文件大小不能超过 1G</div>
		            </el-upload>
		            <div v-if="addForm.indexImgUrl">上传文件大小不能超过 1G</div>
		            <el-progress v-show="showProgress" :text-inside="true" :stroke-width="15" :percentage="progress"></el-progress>
                </el-form-item>
				
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button size="mini" @click.native="addFormVisible = false">取消</el-button>
				<el-button size="mini" type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
		<!--编辑界面-->
		<el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false" width="500px">
			<el-form :model="editForm" label-width="80px" ref="editForm">
				<el-form-item label="名称" prop="indexName"  :rules="[{ required: true, message: '请填写名称', trigger: 'blur' }]">
                    <el-input v-model="editForm.indexName" />
                </el-form-item>
                <el-form-item label="描述" prop="indexDescription" :rules="[{ required: true, message: '请填写描述', trigger: 'blur' }]">
                    <el-input v-model="editForm.indexDescription"/>
                </el-form-item>
                <el-form-item label="排序" prop="sort" :rules="[{ required: true, message: '请填写排序', trigger: 'blur' }]">
                    <el-input v-model="editForm.sort"/>
                </el-form-item>
				<!--<el-form-item label="图片:" prop="indexImgUrl" :rules="[{ required: true, message: '请上传图片', trigger: 'blur' }]">
					<el-upload class="avatar-uploader photo" list-type="picture-card" :http-request="(res)=>{return Upload2(res, 'indexImgUrl')}" :multiple="false" :show-file-list="false" action="" :before-upload="beforeAvatarUpload" accept="image/jpeg,image/png">
						<img v-if="editForm.indexImgUrl" :src="editForm.indexImgUrl" class="avatar" width="145" height="145">
						<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					</el-upload>
				</el-form-item>-->
				<el-form-item label="视频">
					<div v-if="editForm.indexImgUrl" class="uploadVideo">
						<video :src="editForm.indexImgUrl" :poster="editForm.vodPhoto" controls style="width: 360px;height: 180px;"></video>
						<img class="uploadImgItemDel" @click="handleDelUrl(1)" src="http://blyw.oss-cn-hangzhou.aliyuncs.com/webStorage/web_1619754060794173.png"/>
					</div>
					<el-upload v-if="!editForm.indexImgUrl" action :http-request="UploadE" :on-preview="handlePreview" :before-remove="beforeRemove" :on-remove="handleRemove" :on-success="handleSuccess" :on-exceed="handleExceed" drag :limit="limit" :file-list="fileList">
				        <i class="el-icon-upload" ></i>
				        <div class="el-upload__text">
					                       将视频拖到此处，或
					        <em>点击上传</em>
				        </div>
			            <div slot="tip" class="el-upload__tip">上传文件大小不能超过 1G</div>
		            </el-upload>
		            <div v-if="editForm.indexImgUrl">上传文件大小不能超过 1G</div>
		            <el-progress v-show="showProgress" :text-inside="true" :stroke-width="15" :percentage="progress"></el-progress>
                </el-form-item>
				
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button size="mini" @click.native="editFormVisible = false">取消</el-button>
				<el-button size="mini" type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>
		<!--播放视频界面-->
		<el-dialog title="视频" :visible.sync="playFormVisible" :close-on-click-modal="false" width="850px">
		  <video :src="data.indexImgUrl" :poster="data.indexImgUrl + '?x-oss-process=video/snapshot,t_10000,m_fast'" controls style="width: 800px;"></video>
		</el-dialog>
	</section>
</template>

<script>
	import { client,getFileNameUUID } from '../../common/js/alioss'
	import util from '../../common/js/util'

	export default {
		props: {
			limit: {
				type: Number,
				default: 1
			}
		},
		data() {
			return {
				
				filters: {
					content: '',
				},
				
                data:{},
				users: [],
				data:[],
				sels: [],
				total: 0,
				page: 1,
				pageSize: 10,
				listLoading: false,
				
				
				addFormVisible: false,
				addLoading: false,
				addForm: {
					indexDescription: '',
					indexImgUrl:'',
					indexName:'',
					sort:'',
				},
				editFormVisible: false,
				editLoading: false,
				editForm: {
					indexId: '',
					indexDescription: '',
					indexImgUrl:'',
					indexName:'',
					sort:'',
				},
				ileList: [], //文件列
		        showProgress: false, //进度条的显示
		        dataObj: {}, //存签名信息
		        progress: 0, //进度条数据
		        fileList:[],
				playFormVisible: false,
				data:{},
			}
		},
		
		methods: {
			//二级
			indexChild(index, row, href) {
				console.log(href, '1')
				this.$router.push({
					path: '/' + href,
					query: {
						id: row.indexId
					}
				})
			},
			//添加图片
			dialogClose(){
                this.fileList = [];
            },
			
			beforeAvatarUpload(file) {
//              this.listLoading = true;
			},//图片上传到阿里云
            Upload1(file, index) {
				var fileName = 'webStorage/web_' + file.file.uid+Math.floor(Math.random()*10000) + file.file.name.substr(file.file.name.indexOf("."));
				client().put(fileName, file.file).then(result => {
					this.addForm[index] = result.url;
					console.log(this.addForm[index]);
				}).catch(function (err) {
                    console.log(err);
	 			});
            },
            Upload2(file, index) {
				var fileName = 'webStorage/web_' + file.file.uid+Math.floor(Math.random()*10000) + file.file.name.substr(file.file.name.indexOf("."));
				client().put(fileName, file.file).then(result => {
					this.editForm[index] = result.url;
				}).catch(function (err) {
                    console.log(err);
	 			});
            },
            // 文件超出个数限制时的钩子
			handleExceed(files, fileList) {
				this.$message.warning(`每次只能上传 ${this.limit} 个文件`);
			},
			// 点击文件列表中已上传的文件时的钩子
			handlePreview(file) {},
			// 删除文件之前的钩子
			beforeRemove(file, fileList) {
				return this.$confirm(`确定移除 ${file.name}？`);
			},
			// 文件列表移除文件时的钩子
			handleRemove(file, fileList) {},
			// 文件上传成功时的钩子
			handleSuccess(response, file, fileList) {
				this.fileList = fileList;
			},
			//文件上传前的校验
			beforeAvatarUploadV(file) {
				const isLt100M =
					file.size / 1024 / 1024 > 10 && file.size / 1024 / 1024 < 1024;
				const isLt30 = file.name.length < 30;
				if (["video/mp4"].indexOf(file.type) == -1) {
					this.$message.error("请上传正确的视频格式");
					return false;
				}
				if (!isLt100M) {
					this.$message.error("上传视频大小要在10MB~1GB之间哦!");
					return false;
				}
				if (!isLt30) {
					this.$message.error("上传视频文件名称长度必须要小于30个文字哦!");
					return false;
				}
			},
			// http-request属性来覆盖默认的上传行为（即action="url"），自定义上传的实现
			//multipartUpload方法查看官方文档[添加链接描述](https://www.alibabacloud.com/help/zh/doc-detail/31995.htm)
			Upload(file) {
				const that = this;
				async function multipartUpload() {
					let temporary = file.file.name.lastIndexOf(".");
					let fileNameLength = file.file.name.length;
					let fileFormat = file.file.name.substring(
						temporary + 1,
						fileNameLength
					);
					console.log(getFileNameUUID(),'getFileNameUUID()');
					console.log(fileFormat,'fileFormat');
					let fileName = getFileNameUUID() + "." + fileFormat;
					client(that.dataObj)
						.multipartUpload(`beizhi/${fileName}`, file.file, {
							progress: function(p) {
								//p进度条的值
								console.log(p);
								that.showProgress = true;
								that.progress = Math.floor(p * 100);
							}
						})
						.then(result => {
							//上传成功返回值，可针对项目需求写其他逻辑
							console.log(result,'上传成功了')
							var url = result.res.requestUrls[0]
							var index = url.lastIndexOf("?")
							url = url.substring(0, index)
							console.log(url,'新的链接')
							that.addForm.indexImgUrl = url;
		                    //that.addForm.coverUrl = url + '?x-oss-process=video/snapshot,t_10000,m_fast';
//							let audioElement = new Audio(url);
//							audioElement.addEventListener("loadedmetadata", () => {
//							    that.addForm.duration = Math.floor(audioElement.duration); //时长为秒，小数，182.36
//							    console.log(that.addForm.duration,'duration');
//							});
						})
						.catch(err => {
							console.log("err:", err);
							console.log("上传失败了", err);
						});
				}
				multipartUpload();

			},
			UploadE(file) {
				const that = this;
				async function multipartUpload() {
					let temporary = file.file.name.lastIndexOf(".");
					let fileNameLength = file.file.name.length;
					let fileFormat = file.file.name.substring(
						temporary + 1,
						fileNameLength
					);
					console.log(getFileNameUUID(),'getFileNameUUID()');
					console.log(fileFormat,'fileFormat');
					let fileName = getFileNameUUID() + "." + fileFormat;
					client(that.dataObj)
						.multipartUpload(`beizhi/${fileName}`, file.file, {
							progress: function(p) {
								//p进度条的值
								console.log(p);
								that.showProgress = true;
								that.progress = Math.floor(p * 100);
							}
						})
						.then(result => {
							//上传成功返回值，可针对项目需求写其他逻辑
							console.log(result,'上传成功了')
							var url = result.res.requestUrls[0]
							var index = url.lastIndexOf("?")
							url = url.substring(0, index)
							console.log(url,'新的链接')
							that.editForm.indexImgUrl = url;
		                    //that.editForm.coverUrl = url + '?x-oss-process=video/snapshot,t_10000,m_fast';
//							let audioElement = new Audio(url);
//							audioElement.addEventListener("loadedmetadata", () => {
//							    that.editForm.duration = Math.floor(audioElement.duration); //时长为秒，小数，182.36
//							    console.log(that.editForm.duration,'duration');
//							});
						})
						.catch(err => {
							console.log("err:", err);
							console.log("上传失败了", err);
						});
				}
				multipartUpload();

			},
			//删除视频
			handleDelUrl(index){
				if (index==0) {
					this.addForm.indexImgUrl = ''
				}else{
					this.editForm.indexImgUrl = ''
				}
				this.showProgress = false //进度条的显示
		        this.dataObj = {} //存签名信息
		        this.progress = 0 //进度条数据
			},
			//显示播放视频界面
			handlePlay: function (row) {
			    console.log(row)
			    this.playFormVisible = true;
			    this.data = row
			},
			handleCurrentChange(val) {
				this.page = val;
				this.getUsers();
			},
			//获取用户列表
			getUsers:function (){
				this.listLoading = true;
				let para = {
					page: this.page,
					size: this.pageSize,
					content: this.filters.content,
				};
				var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
			    });  
			    instance.post('admin/platform/manage/getHomeModuleParentList', this.qs.stringify(para)).then(data => {
					let  res = data.data;
					console.log(data);
					if (res.code !== 0) {
						this.$message({
							message: res.msg,
							type: 'error'
						});
					} else {
						this.total = res.total;
						this.users = res.rows;
						this.listLoading = false;
					}
				});
			},
			
			selsChange: function (sels) {
				this.sels = sels;
			},
			//显示新增界面
			handleAdd: function () {
				this.addFormVisible = true;
				this.addForm = {
					indexDescription: '',
					indexImgUrl:'',
					indexName:'',
					sort:'',
				};
			},
			//新增
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
                            let para = Object.assign({}, this.addForm);
                            var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
						    });  
						    instance.post('admin/platform/manage/addOrUpdHomeModuleParent', this.qs.stringify(para)).then(data => {
								let  res = data.data;
								if (res.code !== 0) {
									this.$message({
										message: res.msg,
										type: 'error'
									});
								} else {
									this.addLoading = false;
									this.$message({
										message: '成功',
										type: 'success'
									});
									this.$refs['addForm'].resetFields();
									this.addFormVisible = false;
									this.getUsers();
								}
							});
						});
					}
				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.showProgress = false //进度条的显示
		        this.dataObj = {} //存签名信息
		        this.progress = 0 //进度条数据
				this.editFormVisible = true;
				this.editForm.indexId = row.indexId;
				this.editForm.indexDescription = row.indexDescription;
				this.editForm.indexImgUrl = row.indexImgUrl;
				this.editForm.indexName = row.indexName;
				this.editForm.sort = row.sort;
			},
			//编辑
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.editLoading = true;
							let para = {
								indexId:this.editForm.indexId,
								indexDescription:this.editForm.indexDescription,
								indexImgUrl:this.editForm.indexImgUrl,
								indexName:this.editForm.indexName,
								sort:this.editForm.sort,
							}
							var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
						    });  
						    instance.post('admin/platform/manage/addOrUpdHomeModuleParent', this.qs.stringify(para)).then(data => {
								
								let  res = data.data;
								if (res.code !== 0) {
									this.$message({
										message: res.msg,
										type: 'error'
									});
								} else {
									this.editLoading = false;
									this.$message({
										message: '提交成功',
										type: 'success'
									});
									this.$refs['editForm'].resetFields();
									this.editFormVisible = false;
									this.getUsers();
								}
							});
						});
					}
				});
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id).toString();
				this.handleDel(ids);
			},
			//删除
			handleDel(indexId) {
				this.$confirm('确认删除以及子级分类吗?', '提示', {}).then(() => {
					this.listLoading = true;
					var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
				    });  
				    instance.post('admin/platform/manage/delHomeModuleParent', this.qs.stringify({indexId: indexId})).then(data => {
						
						let  res = data.data;
						if (res.code !== 0) {
							this.$message({
								message: res.msg,
								type: 'error'
							});
						} else {
							this.$message({
								message: '成功',
								type: 'success'
							});
							this.getUsers();
						}
					})
				}).catch(() => {

				});
			},
		},
		mounted() {
			this.getUsers();
		}
	}

</script>
<style>

</style>

<style>
	.advice{
		margin-left: 80px;
		margin-bottom: 10px;
		font-size: 12px;
	}
</style>

